﻿using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Brain.Rendering;

namespace Brain.Ballistics3D
{
    public class DefaultBulletRendererTexture3D : IBulletRenderer3D
    {
        protected Texture2D Texture;

        protected Quad Quad;

        protected BasicEffect BasicEffect;

        public DefaultBulletRendererTexture3D(string texture)
        {
            this.ManagerUpdatesBullets = false;

            Quad = new Quad();

            Texture = Engine.Instance.ContentManager.Load<Texture2D>(texture);

            BasicEffect = new BasicEffect(Engine.Instance.GraphicsDevice);
            BasicEffect.Texture = Texture;
            BasicEffect.TextureEnabled = true;
        }

        public void Render(BulletManager3D bulletManager)
        {
            ICamera3D Camera = Engine.Instance.CameraManager.Camera3D;
            if (Camera != null)
            {
                GraphicsDevice device = Engine.Instance.GraphicsDevice;
                device.RasterizerState = RasterizerState.CullNone;
                device.BlendState = BlendState.AlphaBlend;
                device.DepthStencilState = DepthStencilState.Default;
                Viewport viewport = device.Viewport;

                BasicEffect.View = Camera.View;
                BasicEffect.Projection = Camera.Projection;

                for (int i = 0; i < bulletManager.Bullets.Length; i++)
                {
                    Bullet3D bullet = bulletManager.Bullets[i];
                    if (bullet.Active)
                    {
                        if (!this.ManagerUpdatesBullets)
                        {
                            bullet.Update();
                        }

                        BasicEffect.World = Matrix.CreateRotationY(MathHelper.ToRadians(90)) * 
                            Matrix.CreateBillboard(bullet.Position, Camera.Position,
                            Vector3.Up, null);
                        BasicEffect.CurrentTechnique.Passes[0].Apply();
                        Quad.DrawQuad();
                    }
                }

                device.RasterizerState = RasterizerState.CullCounterClockwise;
            }
        }

        public bool ManagerUpdatesBullets { get; set; }


        public void UpdateParticle(Bullet3D particle, int index)
        {
        }
    }
}
